package appbuilder.application.config.builder;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import appbuilder.application.Application;
import appbuilder.application.Context;
import appbuilder.builder.Builder;

/**
 * @author Bruno Gama Catão
 * @since 2007-12-28
 */
public abstract class ConfigBuilder implements Builder {
    private static Logger logger = Logger.getLogger(ConfigBuilder.class.getName());
    
    private static final String UTIL_PACKAGE = "util";
    
    private Application application;
    private VelocityContext context;
    
    public ConfigBuilder(Application application) {
        this.application = application;
        this.context = Context.getInstance().getContext();
    }

    public void build() {
        logger.info("Deleting the source directory");
        deleteFile(getApplication().getBaseDirectory() + File.separator + getApplication().getSourceDirectory());
        logger.info("Deleting the build directory");
        deleteFile(getApplication().getBaseDirectory() + File.separator + getApplication().getBuildDirectory());
        logger.info("Deleting the distribution directory");
        deleteFile(getApplication().getBaseDirectory() + File.separator + getApplication().getDistributionDirectory());
        try {
            logger.info("Generating MessageUtil class");
        	generateMessageUtil();
        } catch (Exception ex) {
        	logger.log(Level.SEVERE, null, ex);
        }
    }
    
    private void generateMessageUtil() throws ResourceNotFoundException, ParseErrorException, Exception {
        context.put("package", buildPackage(UTIL_PACKAGE));

        Template template = Velocity.getTemplate("templates/util/MessageUtil.vm");
        
        File path = createDir(getBaseDirectory() + "." + UTIL_PACKAGE);
        File file = new File(path, "MessageUtil.java");
        
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        
        template.merge(context, writer);
        
        writer.flush();
        writer.close();
    }
    
    private String buildPackage(String suffix) {
        return getApplication().getBasePackage() + "." + suffix;
    }
    
    private String getBaseDirectory() {
        return getApplication().getBaseDirectory() + "." + 
                getApplication().getSourceDirectory() + "." + 
                getApplication().getBasePackage();
    }
    
    protected File createDir(String pkgName) {
        String dirName = pkgName.replace('.', '/');

        File baseDir = new File(dirName);
        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }
        
        return baseDir;
    }
    
    private void deleteFile(String filename) {
        deleteFile(new File(filename));
    }
    
    private void deleteFile(File file) {
        if (!file.exists()) {
            return;
        }
        
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                deleteFile(f);
            }
        }
        
        file.delete();
    }

    public Application getApplication() {
        return application;
    }

    public void setApplication(Application application) {
        this.application = application;
    }
}
